package com.indusfo.spc.common.utlis;

import org.apache.log4j.Logger;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * @ClassName IoUtils
 * @Desription
 * @Author yujn
 * @Date 2018/12/10 下午3:55
 **/
public class IOUtils {

    private static Logger logger = Logger.getLogger(IOUtils.class);


    /**
     * @Description: 加载[外部]配置文件
     * @Params: [propsPath:配置文件绝对路径]
     * @Returns: java.util.Properties
     * @author: 余家能
     * @date: 2018/12/12 下午2:46
     */
    public static Properties loadConfig(String propsPath) {

        Properties props = null;
        InputStreamReader in =null;
        try{
            props = new Properties();
            in = new InputStreamReader(new FileInputStream(propsPath), "UTF-8");
            props.load(in);
            logger.info("配置文件加载成功！propsPath="+propsPath);
        }catch (Exception e){
            logger.error("配置文件加载失败！propsPath="+propsPath,e);
        }finally {
            try {
                if (in!=null){
                    in.close();
                }
            } catch (IOException e) {
                logger.error("关闭资源失败！",e);
                e.printStackTrace();
            }
        }
        return props;
    }


    /**
     * @Description: 通过getResourceAsStream加载配置文件
     * IOUtils.loadPropByStream("/property/test.properties");
     * @Params: [propsPath：相对路径]
     * @Returns: java.util.Properties
     * @author: 余家能
     * @date: 2018/12/12 下午2:46
     */
    public static Properties loadPropByStream(String propsPath){

        Properties prop = new Properties();
        InputStreamReader inputStreamReader = null;
        //相对路径，就是classes路径下

        try {
            inputStreamReader =
                    new InputStreamReader(new IOUtils().getClass().getResourceAsStream(propsPath), "UTF-8");
            prop.load(inputStreamReader);

        } catch (Exception e) {
            logger.error("配置文件加载失败！propsPath="+propsPath,e);
        } finally {
            try {
                if (inputStreamReader!=null){
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                logger.error("关闭资源失败！",e);
                e.printStackTrace();
            }
        }
        return prop;
    }


    /**
     * @Description: 根据规则获取当天文件名称,2018-12-10）20181210.suffix
     * @Params: [suffix：文件后缀]
     * @Returns: java.lang.String 文件名
     * @author: 余家能
     * @date: 2018/12/12 下午2:43
     */
    public static String getTodayFileName(String suffix) {
        String fileName = null;
        // 根据规则生成文件名
        fileName = new SimpleDateFormat("yyyy-MM-dd")
                .format(new Date(System.currentTimeMillis()))
                .replaceAll("-","")+".hex";
        return fileName;
    }


    /**
     * @Description: 文件复制
     * @Params: [targetFilePath, copyFilePath]
     * @Returns: void
     * @author: 余家能
     * @date: 2018/12/12 下午2:43
     */
    public static void copyFile(String targetFilePath,String copyFilePath)  {
        File file = new File(targetFilePath);
        File copy = new File(copyFilePath);

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;

        try{
            bos = new BufferedOutputStream(new FileOutputStream(copy));
            bis = new BufferedInputStream(new FileInputStream(file));

            byte[] bt = new byte[1024*5];
            int len = 0;
            while ((len=bis.read(bt))!=-1){
                bos.write(bt,0,len);
            }
            // 刷新此缓冲的输出流
            bos.flush();
        } catch (FileNotFoundException e){
            logger.error("文件未找到！targetFilePath:"+targetFilePath,e);
        } catch (Exception e){
            logger.error("[未知错误！]copyFile",e);
        }finally {
            try {
                if (bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
                logger.error("关闭输出流失败！",e);
            } finally {
                bos=null;
            }

            try {
                if (bis!=null){
                    bis.close();
                }
            } catch (IOException e){
                logger.error("关闭输入流失败！",e);
            } finally {
                bis=null;
            }
        }
    }

    /**
     * @Description: 删除指定目录下的所有文件
     * @Params: [dir：目录]
     * @Returns: void
     * @author: 余家能
     * @date: 2018/12/12 下午2:40
     */
    public static void deleteFiles(String dir) {

        try {
            File file = new File(dir);
            File[] files = file.listFiles();
            for (File f : files
            ) {
                if (f.exists()) {
                    f.delete();
                }
            }
        } catch (NullPointerException e) {
            logger.error("目录不存在！dir:" + dir);
        }
    }



    /**
     * @Description: 根据系统环境获取类路径
     * @Params: [o]
     * @Returns: java.lang.String
     * @author: 余家能
     * @date: 2018/12/13 下午4:24
     */
    public static String getClassPath(Object o){

        /*
    ide启动：项目路径：/Users/yujn/Documents/WorkSplace/IdeaProjects/edsf/EDSF-COM/IEIS2-COM/target/IEIS2-COM-0.0.1-SNAPSHOT/WEB-INF/classes/
    tomcat服务器启动：项目路径：/Users/yujn/Documents/服务器/apache-tomcat-7.0.91/webapps/ROOT/WEB-INF/classes/
     */
        String classPath = o.getClass().getResource("/").getPath();

        // 判断当前系统
        String systemName = System.getProperty("os.name");
        if (systemName.contains("Mac")){
            logger.info("mac:"+classPath);
        } else if (systemName.contains("Windows")){
            classPath = classPath.replaceFirst("/", "");
            logger.info("windows:"+classPath);
        }

        return classPath;
    }

    /**
     * @Description: 获取项目根路径 xxxx/ROOT/
     * @Params: [o]
     * @Returns: java.lang.String
     * @author: 余家能
     * @date: 2018/12/13 下午4:29
     */
    public static  String getProjectRootPath(Object o){
        String classPath = getClassPath(o);
        String s = classPath.replaceAll("WEB-INF/classes/", "");
        return  s;
    }


    /**
     * @Description: 获取当前项目名
     * @Params: [o]
     * @Returns: java.lang.String
     * @author: 余家能
     * @date: 2018/12/13 下午4:29
     */
    public static  String getProjectName(Object o){
        String classPath = getClassPath(o);
        String s = classPath.replaceAll("/WEB-INF/classes/", "");
        int i = s.lastIndexOf("/");
        String substring = s.substring(i+1);
        return  substring;
    }


    /**
     * @Description: 以当前项目根路径为基础 添加一部分路径
     * xxxx/tomcatxxx/webapps/ROOT/xxxxx/WEB-INF/classes/xxx.class
     * 传入relativeDir: materials-import/ 调用这个方法后
     * xxxx/tomcatxx/webapps/materials-import/
     *
     * @Params: [o]
     * @Returns: java.lang.String
     * @author: 余家能
     * @date: 2018/12/13 下午4:29
     */
    public static  String getPathByProjectRootPath(Object o, String relativeDir){
        String classPath = getClassPath(o);
        String s = classPath.replaceAll("/WEB-INF/classes/", "");

        // 项目名称给替换掉 ROOT 替换成传入的 relativeDir
        String projectName = getProjectName(o);
        String s1 = s.replace(projectName,"");
        s1 = s1+relativeDir;
        return  s1;
    }

    /***
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static  boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /***
     * 删除文件夹
     *
     * @param
     */
    public  static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: junit测试方法
     * @Params: []
     * @Returns: void
     * @author: 余家能
     * @date: 2018/12/12 下午2:41
     */
//    @Test
//    public void testUtils(){
//
//        String path = "/Users/yujn/Documents/WorkSplace/IdeaProjects/edsf/EDSF-COM-2.0/target/IEIS2-COM-0.0.1-SNAPSHOT/materialseat-import";
//        delAllFile(path);
//
//    }
}
